# -*- coding: utf-8 -*-
'''
Created on 21 mars 2011

@author: bressu
'''

 
from web900.core import Filemanager, Phone, AddressBook, CommandQueue, Device,\
    Application, AccountManager, ObjectNotFound, AuthorizationManager


# ---------   function called by presentation layer e.g mod_python through psp ------------




def check_perm(user, object):
    """
    Check the permission of the loggued user to a given object
    """
    return AuthorizationManager(user).check_perm(object)

def getStatus(user):
    """
    Return the status of the device which is associated with the loggued user
    """
    return Device(user).getStatus()

def getAddressBook(user):
    """
    Return the contact list for the loggued user.
    This is a generator    
    """
    for contact in AddressBook(user).generate_address_book():
        yield contact 

def getLocation(user):
    """
    Return the last location of the device
    """
    loc = None
    try:
        loc = Device(user).get_location()
    except ObjectNotFound:
        pass
    return loc
    
    
def iterate_on_account(user):
    for u in AccountManager(user).getAllAccount():
        yield u
    

def getOwnedDevice(user):
    """
    Return the device owned by the current user
    """
    return Device(user).getOwnedDevice()
    
def getDevice(user, owned_by_user):
    """
    Return the device used by an user. The user may not be the owner of the device
    """
    return AccountManager(user).getDevice(owned_by_user)



def getGuess(user):
    """
    Return the guess user for the current user.
    This is a generator
    """
    for g in AccountManager(user).getGuess():
        yield g
    
# ---------   function called by http layer e.g. mod_python through action.py  ------------

def getUserFromApiKey(key):
    actmgr = AccountManager(None)
    return actmgr.getUserFromApiKey(key)


def revoke_guess(user, guess):
    AccountManager(user).delete_guess(guess)

def addGuess(user,login, password):
    """
    Add a new guest on the device owned by the curent user
    """
    return AccountManager(user).create_guess(login, password)


def update_user(user, name, password):
    return AccountManager(user).update_user(name=name, password=password)

def change_api_key(user):
    """
    Generate a new API key for the user
    """
    AccountManager(user).change_api_key()
    
def signin(login, password):
    """
    verify that the given user and password are valid     
    Return an User instance on succesfull validation
    """
    actmgr = AccountManager(None)
    return actmgr.validate(login, password)
    
def signup(login, password):
    """
    Create a new user account
    """
    user = None
    try :
        user = AccountManager(None).create(login, password)
    except:
        raise
    return user
    

def push_status(user, data):
    Device(user).push_status(data)    

def push_location(user, lat ,long, fix):       
    Device(user).push_location(lat, long, fix)
  
def push_address_book(user, **kwargs):
    AddressBook(user).push_address_book(**kwargs)

def shutdown(user):
    CommandQueue(user).post_shutdown_cmd()   

#def add_cmd_listener(user):
#    last_noise = time.time();
#    while True:        
#        listing = os.listdir(N900_COMMAND_DIR)
#        for f in listing :
#            filepath = os.path.join(N900_COMMAND_DIR, f)
#            if os.path.isfile(filepath):
#                req.connection.write("1") 
#                break
#        else:
#            now = time.time()
#            if  now - last_noise > 60:
#                req.connection.write("0")    
#                last_noise = now               
#            time.sleep(1)  

def poll_command(user):
    return CommandQueue(user).poll_command()

def ring_my_bell(user):
    Phone(user).ring_my_bell()

def call(user, number):
    Phone(user).call(number)   

def lock_device(user):
    Device(user).lock_device()


def unlock_device(user):
    Device(user).unlock_device()
            
def open_url(user, url):
    Application(user).open_url( url)


def send_im(user, content):
    Device(user).display_im(content)

def send_sms(user, recipient, content):
    Phone(user).send_sms(recipient, content)


def getPendingDownload(user):
    for f in  Filemanager(user).getPendingDownload():
        yield f

def delete_uploaded_file(user, filename, filekey):
    """
    The device use this action to delete an uploaded file
    after it have successfully download it 
    """
    
    Filemanager(user).delete_uploaded_file(filename, filekey)
    
    
def upload_file(user, file, filename):
    """
    This action is used to push a file on the device.
    """
    Filemanager(user).upload_file(file, filename)
  


    